package com.youdianstar.app.ui.util

import android.app.Dialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.youdianstar.app.R


/**
 * File: CityPickerDialog
 * Author: Assistant Create: 2024/12/19
 * Changes (from 2024/12/19)
 * --------------------------------------------------
 * description: 城市选择器对话框
 * ---------------------------------------------------
 *
 */
class CityPickerDialog(
    context: Context,
    private val cities: List<String>,
    private val onCitySelected: (String) -> Unit
) {

    private var dialog: BottomSheetDialog = BottomSheetDialog(context)

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_city_picker, null)
        dialog.setContentView(view)

        val recyclerView: RecyclerView = view.findViewById(R.id.rv_city)
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = CityAdapter(cities) { city ->
            onCitySelected(city)
            dialog.dismiss()
        }
    }

    fun show() {
        dialog.show()
    }

    fun dismiss() {
        dialog.dismiss()
    }

    class CityAdapter(
        private val cities: List<String>,
        private val onItemClick: (String) -> Unit
    ) : RecyclerView.Adapter<CityAdapter.ViewHolder>() {

        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val textView: TextView = itemView.findViewById(R.id.tv_city_item)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_city, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.textView.text = cities[position]
            holder.itemView.setOnClickListener {
                onItemClick(cities[position])
            }
        }

        override fun getItemCount() = cities.size
    }
}

